package com.hutao.medical.common.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.List;

import javax.imageio.ImageIO;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.SimpleDoc;

import com.hutao.medical.pojo.dto.PrintPageDto;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;

public class PDFUtil {

	public static ByteArrayOutputStream getPDFStream(List<PrintPageDto> publishImages) throws MalformedURLException, IOException, DocumentException{
    	ByteArrayOutputStream bos = new ByteArrayOutputStream();
    	Document document = new Document(PageSize.A4); 
    	document.setMargins(0, 0, 0, 0);
    	PdfWriter.getInstance(document, bos);
		
		document.open();
		// Code 2
      /*
		Map<String, String> pageTypes = new HashMap<String, String>();
		List<String> pageTypeCodes = new ArrayList<String>();*/
//		int index =0;
		for (PrintPageDto imageFile : publishImages) {
//			index ++;
//			if(index == 3){
//				break;
//			}
			/*Image image = Image.getInstance(BarCodeUtil.generate("123456789"));*/
			String imagePath = imageFile.getPrintImagePath();
        	/*String pageTypeCode = (String)(String)imageFile.get("mr_page_type_code");
        	String pageTypeName = (String)(String)imageFile.get("page_type_name");
        	if(pageTypeCode == null){
        		pageTypeCode = "-01";
        		pageTypeName = "未编页";
        	}
        	*/
			Image image = Image.getInstance(imagePath);
			float imageHeight=image.getScaledHeight();
			float imageWidth=image.getScaledWidth();
			if(imageFile.getImageRotation() == 90){
				imageHeight=image.getScaledWidth();
				imageWidth=image.getScaledHeight();
			}
			int i=0;
			while(imageHeight>PageSize.A4.getHeight()||imageWidth>PageSize.A4.getWidth()){
				image.scalePercent(100-i);
				i++;
				imageHeight=image.getScaledHeight();
				imageWidth=image.getScaledWidth();
				if(imageFile.getImageRotation() == 90){
					imageHeight=image.getScaledWidth();
					imageWidth=image.getScaledHeight();
				}
			}
			if(imageFile.getImageRotation() == 90){
				image.setRotationDegrees(90);
			}
			
			/*image.scalePercent(100);*/
			image.setAlignment(Image.ALIGN_CENTER);
			document.newPage();
			/*if(!pageTypes.containsKey(pageTypeCode)){
				document.add(new Chunk(pageTypeName).setLocalDestination(pageTypeCode));
				pageTypes.put(pageTypeCode, pageTypeName);
				pageTypeCodes.add(pageTypeCode);
			}*/
			
			document.add(image);
			
		}
		
		/*PdfContentByte cb = writer.getDirectContent();
		PdfOutline root = cb.getRootOutline();
		for (String pageTypeCode : pageTypeCodes) {
			 @SuppressWarnings("unused")
		     PdfOutline oline1 = new PdfOutline(root, PdfAction.gotoLocalPage(pageTypeCode, false),pageTypes.get(pageTypeCode));
		        
		}*/
		// Code 3  
       
          
        
	 	document.close();
	 	return bos;
    
	}
	
	
	public static synchronized void createPdf(List<PrintPageDto> publishImages,String newPDFPath) throws DocumentException, IOException{
    	Document document = new Document();
    	document.setPageSize(PageSize.A4);
    	FileOutputStream out = null;
    	
		try {
			File newFile = new File(newPDFPath);
			if(!newFile.exists()){
				File parentFile = new File(newFile.getParent());
				if(!parentFile.exists()){
					parentFile.mkdirs();
				}
			}else{
				return;
			}
			out = new FileOutputStream(newPDFPath);
			PdfWriter.getInstance(document, out);
			// 打开文档
			document.open();
			// 读取一个图片
			int index = 0;
			for (PrintPageDto imageFile : publishImages) {
				index ++;
				if(index == 3){
					break;
				}
				String imagePath = imageFile.getPrintImagePath();
	        	
				Image image = Image.getInstance(imagePath);
		        // 添加图片
				float imageHeight=image.getScaledHeight();
				float imageWidth=image.getScaledWidth();
				if(imageFile.getImageRotation() == 90){
					imageHeight=image.getScaledWidth();
					imageWidth=image.getScaledHeight();
				}
				int i=0;
				while(imageHeight>PageSize.A4.getHeight()||imageWidth>PageSize.A4.getWidth()){
					image.scalePercent(100-i);
					i++;
					imageHeight=image.getScaledHeight();
					imageWidth=image.getScaledWidth();
					if(imageFile.getImageRotation() == 90){
						imageHeight=image.getScaledWidth();
						imageWidth=image.getScaledHeight();
					}
				}
				if(imageFile.getImageRotation() == 90){
					image.setRotationDegrees(90);
				}
				image.setAlignment(Image.ALIGN_CENTER);
				document.newPage();
				
				document.add(image);
				
			}
			
		} catch (DocumentException de) {
			de.printStackTrace();
			throw de;
		} catch (IOException ioe) {
			ioe.printStackTrace();
			throw ioe;
		}finally{
			try {
				if(out!= null){
					out.flush();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			try{
				if(document != null){
					document.close();
				}
			}catch (Exception e) {
				// TODO: handle exception
			}
			try {
				if(out!= null){
					out.close();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
    }
	
	
	/*public static synchronized void createPdf(List<PrintPageDto> publishImages,String newPDFPath,String waterImagePath) throws DocumentException, IOException{
    	Document document = new Document();
    	document.setPageSize(PageSize.A4);
    	FileOutputStream out = null;
    	
		try {
			File newFile = new File(newPDFPath);
			if(!newFile.exists()){
				File parentFile = new File(newFile.getParent());
				if(!parentFile.exists()){
					parentFile.mkdirs();
				}
			}else{
				return;
			}
			out = new FileOutputStream(newPDFPath);
			PdfWriter.getInstance(document, out);
			// 打开文档
			document.open();
			// 读取一个图片
			for (PrintPageDto imageFile : publishImages) {
				String imagePath = imageFile.getPrintImagePath();
				BufferedImage buffImg = WaterMarkUtil.getBufferedMarkImageByIcon(waterImagePath, imagePath, 0);
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				ImageIO.write(buffImg,"JPG",bos);
				Image image = Image.getInstance(imagePath);
				Image image = Image.getInstance(bos.toByteArray());
		        // 添加图片
				float imageHeight=image.getScaledHeight();
				float imageWidth=image.getScaledWidth();
				if(imageFile.getImageRotation() == 90){
					imageHeight=image.getScaledWidth();
					imageWidth=image.getScaledHeight();
				}
				int i=0;
				while(imageHeight>PageSize.A4.getHeight()||imageWidth>PageSize.A4.getWidth()){
					image.scalePercent(100-i);
					i++;
					imageHeight=image.getScaledHeight();
					imageWidth=image.getScaledWidth();
					if(imageFile.getImageRotation() == 90){
						imageHeight=image.getScaledWidth();
						imageWidth=image.getScaledHeight();
					}
				}
				if(imageFile.getImageRotation() == 90){
					image.setRotationDegrees(90);
				}
				image.setAlignment(Image.ALIGN_CENTER);
				document.newPage();
				
				document.add(image);
				
			}
			
		} catch (DocumentException de) {
			de.printStackTrace();
			throw de;
		} catch (IOException ioe) {
			ioe.printStackTrace();
			throw ioe;
		}finally{
			try {
				if(out!= null){
					out.flush();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			try{
				if(document != null){
					document.close();
				}
			}catch (Exception e) {
				// TODO: handle exception
			}
			try {
				if(out!= null){
					out.close();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
    }
	*/
	public static synchronized void createPdf(List<PrintPageDto> publishImages,String newPDFPath,String waterMarkFilePath) throws Exception{
		ByteArrayOutputStream baos =WaterMarkUtil.getOutputStreamOfWterMarkByIcon(getPDFStream(publishImages), waterMarkFilePath);
		File newFile = new File(newPDFPath);
		if(!newFile.exists()){
			File parentFile = new File(newFile.getParent());
			if(!parentFile.exists()){
				parentFile.mkdirs();
			}
		}
		FileOutputStream fileOutputStream = new FileOutputStream(new File(newPDFPath));
		fileOutputStream.write(baos.toByteArray());
		fileOutputStream.close();

	}
	
	public static synchronized void createPdf(List<PrintPageDto> publishImages,String newPDFPath,String waterMarkFilePath,String signetFilePath) throws Exception{
		ByteArrayOutputStream baos =WaterMarkUtil.getOutputStreamOfSignetByIcon(WaterMarkUtil.getOutputStreamOfWterMarkByIcon(getPDFStream(publishImages), waterMarkFilePath),signetFilePath);
		File newFile = new File(newPDFPath);
		if(!newFile.exists()){
			File parentFile = new File(newFile.getParent());
			if(!parentFile.exists()){
				parentFile.mkdirs();
			}
		}
		FileOutputStream fileOutputStream = new FileOutputStream(new File(newPDFPath));
		fileOutputStream.write(baos.toByteArray());
		fileOutputStream.close();

	}

	
	
	
	
}
